package com.pagoda.nerp.trade.common.objectutil;

import com.pagoda.nerp.trade.admin.vendor.dto.MdAccountDto;
import com.pagoda.nerp.trade.entity.MdAccount;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 对象工具类：拷贝对象属性
 * <p>
 * Created by Jungle on 2016/12/17.
 */
public class CopyObject {

    private static final Logger logger = LoggerFactory.getLogger(CopyObject.class);

    /**
     * 父类实例对象bean数据复制到子类对象
     * @param father 父类实例对象
     * @param child 子类实例对象
     * @throws Exception
     */
    public static void fatherToChild(Object father, Object child) throws Exception {

        if (!(child.getClass().getSuperclass() == father.getClass())) {
            throw new RuntimeException("child不是father的子类");
        }

        Class fatherClass = father.getClass();
        Field ff[] = fatherClass.getDeclaredFields();
        // 该属性被声明为private 的，需要将setAccessible设置为true. 默认的值为false.
        Field.setAccessible(ff, true);
        for (int i = 0; i < ff.length; i++) {
            // 获取每一个属性
            Field f = ff[i];
            Class type = f.getType();
            Method m = fatherClass.getMethod("get" + upperHeadChar(f.getName()));//方法getDeleteDate
            // 取出属性值
            Object obj = m.invoke(father);
            f.set(child, obj);
        }
    }

    /**
     * 首字母大写，in:deleteDate，out:DeleteDate
     */
    private static String upperHeadChar(String in) {
        String head = in.substring(0, 1);
        String out = head.toUpperCase() + in.substring(1, in.length());
        return out;
    }

    public static void main(String[] args) throws Exception {
        MdAccount mdAccount = new MdAccount();
        mdAccount.setAccountId(1);
        mdAccount.setAccount("15337178625");
        MdAccountDto mdAccountDto = new MdAccountDto();
        CopyObject.fatherToChild(mdAccount, mdAccountDto);
        mdAccountDto.setRoleIds("1,2,3");
        logger.debug("父类数据：{}", mdAccount);
        logger.debug("子类数据:{}", mdAccountDto.getAccount());
    }
}
